import { ContentConfig } from "src/config/defaultconfig";
import { DynamicModule, ModuleMetadata, Provider } from '@nestjs/common';
import * as services from '../service/index';
import { CategoryRepository, CommentRepository, PostRepository } from "src/entity/repositories";

import { TypeOrmModule } from "@nestjs/typeorm";
import * as entities from '../entity/Entity';
import { DatabaseModule } from "src/database/database.module";
import { PostService } from "src/service/Post.Service";
export class ContentModule {
    static forRoot(configRegister?: () => ContentConfig): DynamicModule {
        const config: Required<ContentConfig> = {
            searchType: 'against',
            ...(configRegister ? configRegister() : {})
        }

        const providers: ModuleMetadata['providers'] = [
            ...Object.values(services),
            {
                provide: PostService,
                inject: [PostRepository, CategoryRepository, services.CategoryService, { token: services.SearchService, optional: true }],
                useFactory(postRepository: PostRepository, categoryRepository: CategoryRepository, categoryService: services.CategoryService, searchService?: services.SearchService) {

                    return new PostService(
                        postRepository,
                        categoryRepository,
                        categoryService,
                        searchService,
                    )
                }
            }
        ]
        if (config.searchType == 'elastic') providers.push(services.SearchService)
        return {
            module: ContentModule,
            imports: [TypeOrmModule.forFeature(Object.values(entities)), DatabaseModule.forRepository([PostRepository, CategoryRepository, CommentRepository])],
            providers,
            exports: [...Object.values(services), PostService, , DatabaseModule.forRepository([PostRepository, CategoryRepository, CommentRepository])]
        }


    }
}
